<template>
  <view class="content">
    <view class="register-form">
      <u-form labelPosition="top" :model="form" :rules="rules" ref="uForm">
        <u-form-item label="标题" prop="title" borderBottom>
          <u-input v-model="form.title" placeholder="请输入标题" border="none"></u-input>
        </u-form-item>
        <u-form-item label="房屋图片上传" borderBottom>
          <u-upload :fileList="fileList1" multiple :maxCount="9" @delete="deletePic" @afterRead="afterRead" name="1" />
        </u-form-item>
        <u-form-item label="联系人" prop="contactPerson" borderBottom>
          <u-input v-model="form.contactPerson" placeholder="请输入联系人" border="none"></u-input>
        </u-form-item>
        <u-form-item label="联系电话" prop="contactPhone" borderBottom type="number">
          <u-input v-model="form.contactPhone" placeholder="请输入联系电话" border="none"></u-input>
        </u-form-item>
        <u-form-item label="详细地址" prop="address" borderBottom>
          <u-input v-model="form.address" placeholder="请输入详细地址" border="none">
          </u-input>
        </u-form-item>
        <u-form-item label="位置描述" prop="locationDesc" borderBottom>
          <u-input v-model="form.locationDesc" placeholder="请输入位置描述" border="none"></u-input>
        </u-form-item>
        <u-form-item label="租金" prop="rent" borderBottom>
          <u-input v-model="form.rent" placeholder="请输入租金" border="none" type="number"></u-input>
        </u-form-item>
        <u-form-item label="正文内容" prop="content" borderBottom>
          <u-textarea v-model="form.content" placeholder="请输入正文内容" border="none" />
        </u-form-item>
      </u-form>
    </view>
    <view class="submit">
      <u-button type="primary" text="发布" @click="submit"></u-button>
    </view>
  </view>
</template>

<script>
import communityApi from '../request/api/community'
import { mapState } from 'vuex'
import config from '../request/config'
const baseForm = {
  title: '',
  contactPerson: '',
  contactPhone: '',
  address: '',
  locationDesc: '',
  rent: '',
  content: '',
}
export default {
  data() {
    return {
      form: { ...baseForm },
      rules: {
        title: [{ required: true, message: '请输入标题', trigger: ['blur'] }],
        contactPerson: [{ required: true, message: '请输入联系人', trigger: ['blur'] }],
        contactPhone: [
          { required: true, message: '请填写联系电话', trigger: ['blur'] },
          { pattern: /^1(3[0-9]|4[01]|5[0-9]|6[6]|7[0-9]|8[0-9]|9[0-9])\d{8}$/, message: '请输入正确的手机号', trigger: ['blur'] }
        ],
        address: [{ required: true, message: '请填写详细地址', trigger: ['blur'] }],
        locationDesc: [{ required: true, message: '请填写位置描述', trigger: ['blur'] }],
        rent: [{ required: true, message: '请填写租金', trigger: ['blur'] }],
        content: [{ required: true, message: '请填写正文内容', trigger: ['blur'] }]
      },
      fileList1: []
    }
  },
  computed: {
    ...mapState('userInfo', ['user'])
  },
  async onLoad() {
    await this.$store.dispatch('userInfo/GetInfo')
    if (!this.user.postStatus) return uni.showModal({
      title: '提示',
      content: '该账号未实名认证，请点击我的个人信息填写实名信息，等待管理员认证通过可发布信息。',
      showCancel: false,
      confirmText: '返回',
      success: () => {
        uni.navigateBack();
      }
    })
    this.$refs.uForm.setRules(this.rules)
  },
  methods: {
    back() {
      uni.navigateBack()
    },
    deletePic(event) {
      this[`fileList${event.name}`].splice(event.index, 1)
    },
    async afterRead(event) {
      // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
      let lists = [].concat(event.file)
      // 用于存储符合条件的图片
      let Images = [];
      // 遍历上传的每张图片
      for (let i = 0; i < lists.length; i++) {
        const item = lists[i];
        // 验证图片大小
        const maxSize = 20 * 1024 * 1024; // 2MB大小限制
        if (item.size > maxSize) {
          uni.showToast({
            title: '图片大小不能超过20MB',
            icon: 'none'
          });
          // 删除不符合条件的图片
          lists.splice(i, 1);
          // 跳过当前图片，进行下一张图片的验证
          continue;
        }
        Images.push(item)
      }
      let fileListLen = this[`fileList${event.name}`].length
      Images.map((item) => {
        this[`fileList${event.name}`].push({
          ...item,
          status: 'uploading',
          message: '上传中'
        })
      })
      for (let i = 0; i < Images.length; i++) {
        const result = await uni.$http.upload('/system/user/profile/upload', Images[i].url)
        let item = this[`fileList${event.name}`][fileListLen]
        this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
          status: 'success',
          message: result.status == 'failed' ? '上传失败' : '',
          url: config.baseUrl + result.imgUrl
        }))
        fileListLen++
      }
    },
    back() {
      uni.navigateBack()
    },
    async submit() {
      if (!this.fileList1.length) return uni.$showMsg('请先上传房屋图片')
      await this.$refs.uForm.validate()
      uni.showLoading({
        title: '加载中',
        mask: true,
      });
      const params = {
        ...this.form,
        images: this.fileList1.map(item => item.url.replace(config.baseUrl, '')).join(','),
        userId: this.user.userId,
        type: 1,
      }
      try {
        await communityApi.addCommunity(params)
      } catch (error) {
        return
      } finally {
        uni.hideLoading()
      }
      uni.$showMsg('发布成功')
      setTimeout(() => {
        this.back()
      }, 1000)
    }
  }
}
</script>

<style scoped lang="scss">
.content {
  box-sizing: border-box;
  height: 100vh;
  background-color: #f8f9fa;
  padding-top: 30rpx;
}

.register-form {
  box-sizing: border-box;
  padding: 25rpx 50rpx 35rpx;
  background-color: #fff;
  box-sizing: border-box;
  height: calc(100% - 200rpx);
  overflow-y: auto;

  &::v-deep .u-radio__text {
    margin-right: 15rpx;
  }
}

.submit {
  background-color: #fff;
  height: 200rpx;
  padding: 25rpx 40rpx 0;
}

.content::v-deep .u-form-item__body__left__content__label {
  width: 200rpx;
  margin-bottom: 15rpx;
}
</style>
